<template>
  <div class="sidebar">
    <el-menu
      :default-active="activeMenu"
      class="el-menu-vertical"
      background-color="rgba(0, 0, 0, 0.2)"
      text-color="#fff"
      active-text-color="#4A90E2"
      @select="handleSelect"
    >
      <el-menu-item index="dashboard" @click="goToHome">
        <el-icon><House /></el-icon>
        <span>首页</span>
      </el-menu-item>
      <el-menu-item index="search" @click="goToSearch">
        <el-icon><Search /></el-icon>
        <span>房源搜索</span>
      </el-menu-item>
      <el-sub-menu index="publish">
        <template #title>
          <el-icon><OfficeBuilding /></el-icon>
          <span>发布房源</span>
        </template>
        <el-menu-item index="publish-house" @click="goToPublishNew">发布新房源</el-menu-item>
        <el-menu-item index="my-houses" @click="goToMyHouses">我的房源</el-menu-item>
      </el-sub-menu>
      <!-- 中介申请菜单（非中介用户显示） -->
      <el-sub-menu index="agent" v-if="!isAgent">
        <template #title>
          <el-icon><User /></el-icon>
          <span>中介申请</span>
        </template>
        <el-menu-item index="agent-apply" @click="goToAgentApply">申请中介</el-menu-item>
        <el-menu-item index="agent-status" @click="goToAgentStatus">申请状态</el-menu-item>
        <el-menu-item index="agent-houses" @click="goToAgentHouses">可代理房源</el-menu-item>
      </el-sub-menu>

      <!-- 中介工作台菜单（中介用户显示） -->
      <el-sub-menu index="3" v-if="isAgent">
        <template #title>
          <el-icon><Briefcase /></el-icon>
          <span>中介工作台</span>
        </template>
        <el-menu-item index="agent-dashboard" @click="goToAgentDashboard">工作台首页</el-menu-item>
        <el-menu-item index="available-houses" @click="goToAvailableHouses">可代理房源</el-menu-item>
        <el-menu-item index="my-proxy-houses" @click="goToMyProxyHouses">我的代理房源</el-menu-item>
        <el-menu-item index="appointment-management" @click="goToAppointmentManagement">预约管理</el-menu-item>
      </el-sub-menu>
      <el-sub-menu index="rental">
        <template #title>
          <el-icon><Key /></el-icon>
          <span>租房信息</span>
        </template>
        <el-menu-item index="tenant" @click="goToTenant">租客</el-menu-item>
        <el-menu-item index="landlord" @click="goToLandlord">房东</el-menu-item>
      </el-sub-menu>
      <el-menu-item index="messages" @click="goToMessages">
        <el-icon><ChatLineSquare /></el-icon>
        <span>消息中心</span>
      </el-menu-item>
      <el-menu-item index="profile" @click="goToProfile">
        <el-icon><Setting /></el-icon>
        <span>个人资料</span>
      </el-menu-item>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  House,
  Search,
  OfficeBuilding,
  User,
  Key,
  ChatLineSquare,
  Setting,
  Briefcase
} from '@element-plus/icons-vue'
import api from '@/utils/api'
import { getToken, getUserInfo, canPublishHouse } from '@/utils/auth'

const router = useRouter()
const props = defineProps({
  activeMenu: {
    type: String,
    default: 'dashboard'
  }
})

// 检查用户是否为中介
const isAgent = computed(() => {
  const userInfo = getUserInfo()
  return userInfo && userInfo.role === 4 // 假设中介角色ID为4
})

const handleSelect = (key) => {
  // 这里可以处理菜单选择事件，如果需要的话
}

// 顶部导航栏跳转
const goToHome = () => {
  router.push('/')
}

const goToSearch = () => {
  router.push('/house/search')
}

const goToPublishNew = () => {
  if (!canPublishHouse()) {
    const userInfo = getUserInfo()
    if (userInfo?.role === 4) {
      ElMessage.error('中介用户不能发布房源，请联系管理员')
    } else {
      ElMessage.error('用户角色不符合发布条件，只有普通用户和房东可以发布房源')
    }
    return
  }
  router.push('/house/publish')
}

const goToMyHouses = () => {
  if (!canPublishHouse()) {
    const userInfo = getUserInfo()
    if (userInfo?.role === 4) {
      ElMessage.error('中介用户不能访问我的房源，请联系管理员')
    } else {
      ElMessage.error('用户角色不符合访问条件，只有普通用户和房东可以访问我的房源')
    }
    return
  }
  router.push('/house/my-houses')
}

// 检查用户实名认证状态
const checkIdentityVerification = async () => {
  try {
    const userInfo = getUserInfo()
    if (!userInfo || !userInfo.isIdentityVerified) {
      ElMessageBox.confirm(
        '申请中介需要先完成实名认证，是否前往实名认证页面？',
        '需要实名认证',
        {
          confirmButtonText: '前往认证',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        router.push('/user/identity-verification')
      }).catch(() => {
        ElMessage.info('已取消操作')
      })
      return false
    }
    return true
  } catch (error) {
    console.error('检查实名认证状态失败:', error)
    ElMessage.error('检查认证状态失败，请稍后重试')
    return false
  }
}

// 检查中介申请状态
const checkAgentStatus = async () => {
  try {
    const response = await api.get('/agent/auth/result', {
      headers: {
        'info': getToken()
      }
    })

    console.log('中介申请状态检查响应:', response)

    // 修复API响应结构判断
    if (response.data && response.data.code === '200' && response.data.data) {
      const data = response.data.data  // 注意这里是 response.data.data
      const statusValue = data.verifyStatus !== undefined ? data.verifyStatus : data.certifyStatus
      const verifyStatus = parseInt(statusValue)

      console.log('中介申请状态值:', verifyStatus, '原始值:', statusValue)

      if (verifyStatus === 2) {
        // 已通过中介申请
        return true
      } else if (verifyStatus === 1) {
        // 申请审核中
        ElMessage.warning('您的中介申请正在审核中，请耐心等待审核结果')
        return false
      } else if (verifyStatus === 0) {
        // 申请被拒绝，可以重新申请
        ElMessage.error('您的中介申请未通过审核，请重新申请')
        return false
      } else {
        // 状态值异常
        ElMessage.warning('中介申请状态异常，请联系客服')
        return false
      }
    } else {
      // 没有申请记录或响应异常
      console.log('没有找到中介申请记录')
      ElMessage.warning('您还没有提交中介申请，请先完成申请流程')
      return false
    }
  } catch (error) {
    console.error('检查中介申请状态失败:', error)
    // 区分不同的错误情况
    if (error.response?.status === 404) {
      ElMessage.warning('您还没有提交中介申请，请先完成申请流程')
    } else {
      ElMessage.error('检查中介申请状态失败，请稍后重试')
    }
    return false
  }
}

const goToAgentApply = async () => {
  const isVerified = await checkIdentityVerification()
  if (isVerified) {
    // 检查是否已经申请过中介
    try {
      const response = await api.get('/agent/auth/result', {
        headers: {
          'info': getToken()
        }
      })

      if (response.data && response.data.code === '200' && response.data.data) {
        const data = response.data.data  // 修复API响应结构
        // 使用verifyStatus字段而不是certifyStatus
        const statusValue = data.verifyStatus !== undefined ? data.verifyStatus : data.certifyStatus
        const verifyStatus = parseInt(statusValue)

        console.log('侧边栏检查到的申请状态:', verifyStatus, '原始值:', statusValue)

        if (verifyStatus === 2) {
          // 已通过审核
          ElMessageBox.alert(
            '您的中介申请已通过审核，现在可以使用中介功能了！',
            '申请已通过',
            {
              confirmButtonText: '查看状态',
              type: 'success',
              callback: () => {
                router.push('/agent/status')
              }
            }
          )
          return
        } else if (verifyStatus === 1) {
          // 审核中
          ElMessageBox.alert(
            '您的中介申请正在审核中，管理员将在1-3个工作日内完成审核。您可以在申请状态页面查看详细进度。',
            '申请审核中',
            {
              confirmButtonText: '查看状态',
              type: 'warning',
              callback: () => {
                router.push('/agent/status')
              }
            }
          )
          return
        } else if (verifyStatus === 0) {
          // 审核未通过，可以重新申请
          ElMessageBox.confirm(
            '您之前的申请未通过审核，可以修改申请信息后重新提交。是否重新申请？',
            '可以重新申请',
            {
              confirmButtonText: '重新申请',
              cancelButtonText: '查看状态',
              type: 'info'
            }
          ).then(() => {
            router.push('/agent/apply')
          }).catch(() => {
            router.push('/agent/status')
          })
          return
        }
      }

      // 没有申请记录，可以申请
      router.push('/agent/apply')
    } catch (error) {
      // 没有申请记录或其他错误，允许申请
      console.log('检查申请状态失败，允许申请:', error)
      router.push('/agent/apply')
    }
  }
}

const goToAgentStatus = () => {
  router.push('/agent/status')
}

const goToAgentHouses = async () => {
  const isVerified = await checkIdentityVerification()
  if (isVerified) {
    const hasAgentAccess = await checkAgentStatus()
    if (hasAgentAccess) {
      router.push('/agent/houses')
    } else {
      // 如果没有中介权限，引导用户查看申请状态或申请
      router.push('/agent/apply')
    }
  }
}

const goToTenant = () => {
  router.push('/rental/tenant')
}

const goToLandlord = () => {
  router.push('/rental/landlord')
}



const goToMessages = () => {
  router.push('/message')
}

const goToProfile = () => {
  router.push('/profile')
}

// 新增中介工作台导航方法
const goToAgentDashboard = () => {
  router.push('/agent/dashboard')
}

const goToAvailableHouses = () => {
  router.push('/agent/available-houses')
}

const goToMyProxyHouses = () => {
  router.push('/agent/my-proxy-houses')
}

const goToAppointmentManagement = () => {
  router.push('/agent/appointment-management')
}
</script>

<style scoped>
.sidebar {
  width: 260px;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(15px);
  padding: 20px 0;
  min-height: calc(100vh - 80px);
  max-height: calc(100vh - 80px);
  box-shadow: 3px 0 15px rgba(0, 0, 0, 0.3);
  overflow-y: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  margin: 20px 0 20px 20px;
  border-radius: 15px 0 0 15px;
}

.sidebar::-webkit-scrollbar {
  width: 0px;
  background: transparent; /* Chrome/Safari/Webkit */
}

.el-menu-vertical {
  border: none !important;
  height: 100%;
  background: transparent !important;
}

.el-menu-item,
.el-sub-menu__title {
  margin: 8px 15px;
  border-radius: 10px;
  transition: all 0.3s ease;
  padding: 12px 16px;
  font-weight: 500;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: rgba(255, 255, 255, 0.15) !important;
  transform: translateX(5px);
}

.el-menu-item.is-active {
  background-color: rgba(74, 144, 226, 0.3) !important;
  color: #4A90E2 !important;
  border-left: 4px solid #4A90E2;
}

.el-sub-menu .el-menu-item {
  margin-left: 25px;
  padding-left: 20px;
}

@media (max-width: 992px) {
  .sidebar {
    width: 80px;
    margin: 20px 0 20px 10px;
  }

  .el-menu-item span,
  .el-sub-menu__title span {
    display: none;
  }

  .el-menu-item,
  .el-sub-menu__title {
    margin: 8px 10px;
    padding: 12px;
    text-align: center;
  }
}
</style>
